package com.mxx.common.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author: mxx
 * @date: 2021/11/24
 * @time: 10:48
 * @Description: 描述信息
 */
@Slf4j
public class ThreadHelper implements ApplicationListener<ContextClosedEvent> {

    private static ThreadPoolExecutor executor;

    public ThreadHelper() {
        this(new ThreadPoolExecutor(
                4,
                8,
                2,
                TimeUnit.MINUTES,
                new LinkedBlockingDeque<>(),
                new DefaultThreadFactory("ThreadHelper")));
    }

    public ThreadHelper(ThreadPoolExecutor executor) {
        this.executor = executor;
    }

    public void exec(Runnable runnable) {
        executor.execute(runnable);
    }

    public <V> Future<V> exec(Callable<V> callable) {
        return executor.submit(callable);
    }

    public <V> int queueSize() {
        return executor.getQueue().size();
    }

    public <V> int getActiveCount() {
        return executor.getActiveCount();
    }

    public List<Runnable> shutdownNow() {
        if (executor != null && !executor.isShutdown()) {
            return executor.shutdownNow();
        }
        return Collections.emptyList();
    }

    public void shutdown() {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
        }
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        shutdown();
        log.info("thread helper showdown complete !");
    }
}

